$(function () {
  let form = layui.form
  getCateList()

  function getCateList() {
    $.ajax({
      url: '/my/article/cates',
      method: 'GET',
      success: res => {
        console.log(res)

        //模板引擎的做法
        // let htmlTpl = template('cateTpl', res)

        // $('tbody').html(htmlTpl)


        // 使用map，join方法--和模板字符串
        let newdata = res.data.map(function (item) {
          // console.log(item)
          return `
          <tr>
            <td>${item.name}</td>
            <td>${item.alias}</td>
            <td>
              <button type="button" class="layui-btn layui-btn-xs edit-btn" data-id="${item.Id}">编辑</button>
              <button type="button" class="layui-btn layui-btn-xs layui-btn-danger del-btn" data-id="${item.Id}">删除</button>
            </td>
          </tr>
          `
        }).join('')

        $('tbody').html(newdata)
      }
    })
  }


  let layerIndex = null
  //添加分类
  $('#addBtn').click(function () {
    let layer = layui.layer
    layer.open({
      type: 1,
      area: ['500px', '250px'],
      title: '添加分类',
      content: $('#addCateTpl').html()
    })
  })

  $('body').on('submit', '#add-form', function (e) {
    e.preventDefault()
    $.ajax({
      url: '/my/article/addcates',
      method: 'POST',
      data: $(this).serialize(),
      success: res => {
        if (res.status !== 0) {
          return layer.msg(res.message)
        }
        layer.msg('新增分类成功')
        layer.close(layerIndex)
        getCateList()
      }
    })
  })

  //编辑分类
  $('body').on('click', '.edit-btn', function () {
    layerIndex = layer.open({
      type: 1,
      area: ['500px', '250px'],
      title: '添加分类',
      content: $('#editCateTpl').html()
    })

    let artId = $(this).attr('data-id')
    console.log(artId)

    $.ajax({
      method: 'GET',
      url: '/my/article/cates/' + artId,
      success: res => {
        if (res.status !== 0) {
          return layer.msg(res.message)
        }
        form.val('editform', res.data)
      }
    })
  })

  //更新
  $('body').on('submit', '#edit-form', function (e) {
    e.preventDefault()
    $.ajax({
      url: '/my/article/updatecate',
      method: "POST",
      data: $(this).serialize(),
      success: res => {
        layer.close(layerIndex)
        if (res.status !== 0) {
          return layer.msg(res.message)
        }
        layer.msg('编辑程功')
        getCateList()
      }
    })
  })

  //删除
  $('body').on('click', '.del-btn', function (index) {
    let cate_id = $('.del-btn').attr('data-id')
    layer.confirm('确认删除吗', { icon: 3, title: '提示' }, function () {
      $.ajax({
        method: 'GET',
        url: '/my/article/deletecate/' + cate_id,
        success: res => {
          if (res.status !== 0) {
            return layer.msg(res.message)
          }
          layer.msg('成功删除')
          getCateList()
        }
      })

      layer.close(index)
    })
  })
})